package com.solace.activiti7modeler.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.codec.Base64Encoder;
import com.solace.activiti7modeler.service.ProcessImageService;
import com.solace.activiti7modeler.utils.HttpUtils;
import com.solace.activiti7modeler.utils.RestMessage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLEncoder;

@RestController
@RequestMapping("/img")
@Api(tags = {"生成工作流程图"})
public class GeneratorImages {
    @Autowired
    private ProcessImageService processImageService;
    @ApiOperation("根据流程实例id生成图片")
    @GetMapping("{proinstanId}")
    public void generate(@PathVariable("proinstanId") String proinstanId, HttpServletRequest req, HttpServletResponse resp) throws Exception {
        InputStream fis = processImageService.getFlowImgByProcInstId(proinstanId);
        String userAgent = req.getHeader("User-Agent").toLowerCase();
        String fileName = "a.svg";
        //如果是火狐浏览器的话，设置浏览器的编码格式
        if (userAgent.indexOf("firefox") != -1) {
            resp.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("GB2312"), "ISO-8859-1"));
        } else {
            resp.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        }

        //设置response编码
        resp.setCharacterEncoding("UTF-8");
        resp.addHeader("Content-Length", "" + fis.available());
        //设置输出文件类型
        resp.setContentType("text/xml");
        ServletOutputStream os = null;
        try {
            //获取response输出流
            os = resp.getOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                // 输出文件
                os.write(buffer, 0, len);
            }
        } catch (Exception e) {
            if (null != fis) {
                fis.close();
            }
            if (null != os) {
                os.flush();
                os.close();
            }
        }
    }


}
